<template>
  <div>
    <h3>背景</h3>
    <div>
      差不多的业务逻辑， 想要复用自定义的校验方法， 通过传参的方式，做一些细节上的区分
    </div>
    <el-form inline :model="formModel" :rules="rules" ref="form">
      <el-form-item label="最小值" prop="minPrice">
        <el-input v-model="formModel.minPrice"></el-input>
      </el-form-item>
      <el-form-item label="最大值" prop="maxPrice">
        <el-input v-model="formModel.maxPrice"></el-input>
      </el-form-item>

      <div>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'common-validator-fn',
  data () {
    // 常规写法

    const minPriceValidate = (rule, value, callback) => {
      // 这块的逻辑一样的
      if (!value || !value.trim()) return callback('价格不能为空')
      const { minPrice, maxPrice } = this.formModel
      const compare = parseInt(minPrice) > parseInt(maxPrice)

      if (compare) {
        this.$refs['form'].clearValidate(['maxPrice'])
        return callback(`价格${minPrice} 比 ${maxPrice} 大`)
      }

      callback()
    }

    const maxPriceValidate = (rule, value, callback) => {
      // 这块的逻辑一样的
      if (!value || !value.trim()) return callback('价格不能为空')

      const { minPrice, maxPrice } = this.formModel
      const compare = parseInt(minPrice) > parseInt(maxPrice)

      if (compare) {
        this.$refs['form'].clearValidate(['minPrice'])
        return callback(`价格${minPrice} 比 ${maxPrice} 大`)
      }

      callback()
    }

    return {

      rules: {
        minPrice: [
          { required: true, validator: this.check('minPrice', '你好'), trigger: ['change', 'blur'] }
        ],
        maxPrice: [
          { required: true, validator: this.check('maxPrice', '再见'), trigger: ['change', 'blur'] }
        ]
      },
      formModel: {
        minPrice: '',
        maxPrice: ''
      }
    }
  },
  methods: {
    check (params, message) {
      // 如果需要访问 Vue 实例， 必须使用箭头函数
      return (rule, value, callback) => {
        console.log('当前model字段', params)
        const { minPrice, maxPrice } = this.formModel
        const compare = parseInt(minPrice) > parseInt(maxPrice)

        // 在最小的框里面输入值
        if (params === 'minPrice' && compare) {
          this.$refs['form'].clearValidate(['maxPrice'])
          return callback(`价格${minPrice} 比 ${maxPrice} 大 --- ${message}`)
        }

        if (params === 'maxPrice' && compare) {
          this.$refs['form'].clearValidate(['minPrice'])
          return callback(`价格${minPrice} 比 ${maxPrice} 大 --- ${message}`)
        }

        if (!value || !value.trim()) return callback('价格不能为空')
        callback()
      }
    },
    submit () {
      this.$refs['form'].validate(((valid) => {
        console.log(valid)
      }))
    }
  }
}
</script>